import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:intl/intl.dart';
import 'package:percent_indicator/percent_indicator.dart';

// ignore: must_be_immutable
class LeveledReadingHistoryDataGrids extends StatelessWidget {
  LeveledReadingHistoryDataGrids(this.readingHistories);

  final GlobalKey<SfDataGridState> progressReadingHistoryGridkey =
      GlobalKey<SfDataGridState>();

  List<BookItem> readingHistories;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  bool isSchoolAdmin = true;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build leveled reading history DataGrids');

    return Column(children: [
      Expanded(child: _buildDataGrid()),
    ]);
  }

  SfDataGrid _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;
    return SfDataGrid(
      source: ReadHistoryDataGridSource(items: readingHistories),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      key: progressReadingHistoryGridkey,
      showCheckboxColumn: false,
      allowFiltering: true,
      rowsPerPage: 15,
      allowSorting: true,
      allowTriStateSorting: true,
      selectionMode: SelectionMode.single,
      navigationMode: GridNavigationMode.row,
      controller: _dataGridController,
      columns: <GridColumn>[
        GridColumn(
          columnName: 'Title',
          width: isWebOrDesktop ? 240 : 180,
          label: buildDataGridColumnLabel('Title'),
        ),
        GridColumn(
          width: 140,
          allowFiltering: false,
          columnName: 'Completed',
          label: buildDataGridColumnLabel('Completed?'),
        ),
        GridColumn(
          columnName: 'Progress',
          allowFiltering: false,
          width: 180,
          label: buildDataGridColumnLabel('Progress'),
        ),
        // GridColumn(
        //   width: 140,
        //   columnName: 'Read Count',
        //   allowFiltering: false,
        //   label: buildDataGridColumnLabel('ReadCount'),
        // ),
        GridColumn(
          columnName: 'Quiz',
          allowFiltering: false,
          width: isWebOrDesktop ? 120 : 120,
          label: buildDataGridColumnLabel('Quiz'),
        ),
        GridColumn(
          columnName: 'QuizCount',
          allowFiltering: false,
          width: isWebOrDesktop ? 140 : 140,
          label: buildDataGridColumnLabel('QuizCount'),
        ),
        // GridColumn(
        //   columnName: 'LastReadAt',
        //   allowFiltering: false,
        //   width: isWebOrDesktop ? 160 : 140,
        //   label: buildDataGridColumnLabel('LastReadAt'),
        // ),
        GridColumn(
          columnName: 'BookCode',
          allowFiltering: false,
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('BookCode'),
        ),
        GridColumn(
          columnName: 'BookId',
          allowFiltering: false,
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('BookId'),
        ),
      ],
    );
  }
}

class ReadHistoryDataGridSource extends DataGridSource {
  ReadHistoryDataGridSource({required List<BookItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'Title', value: dataGridRow.bookTitle),
              DataGridCell<bool>(
                  columnName: 'Completed', value: dataGridRow.readComplete),
              DataGridCell<int>(
                  columnName: 'Progress', value: dataGridRow.readProgress),
              // DataGridCell<int>(
              //     columnName: 'ReadCount', value: dataGridRow.readCount),
              DataGridCell<bool>(
                  columnName: 'Quiz', value: dataGridRow.quizAvailable),
              DataGridCell<int>(
                  columnName: 'QuizCount', value: dataGridRow.quizCount),
              // DataGridCell<int>(
              //     columnName: 'LastReadAt', value: dataGridRow.lastReadAt),
              DataGridCell<String>(
                  columnName: 'BookCode', value: dataGridRow.bookCode),
              DataGridCell<String>(
                  columnName: 'BookId', value: dataGridRow.bookId),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Title') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    // var bookId = row
                    //     .getCells()
                    //     .where((element) => element.columnName == 'BookId')
                    //     .first
                    //     .value;
                    // var bookTitle = row
                    //     .getCells()
                    //     .where((element) => element.columnName == 'Title')
                    //     .first
                    //     .value;
                    // var bookCode = row
                    //     .getCells()
                    //     .where((element) => element.columnName == 'BookCode')
                    //     .first
                    //     .value;

                    // if (GetPlatform.isWeb ||
                    //     GetPlatform.isDesktop ||
                    //     GetPlatform.isMacOS) {
                    //   launchInWebViewWithJavaScript(
                    //       '${Constants.BaseURL}icr/student/book/$bookId');
                    // }
                    // //  else if (GetPlatform.isDesktop || GetPlatform.isMacOS) {
                    // //   launchDeskTopWebview(
                    // //       '${Constants.BaseURL}icr/student/book/$bookId', bookCode);
                    // // }
                    // else {
                    //   Navigator.pushNamed(
                    //       Get.context as BuildContext, '/student/book',
                    //       arguments: BookArguments(
                    //           bookId,
                    //           bookCode,
                    //           bookTitle,
                    //           null,
                    //           NanhaiBookReadingTypes.progressReadingHistory,
                    //           null));
                    // }
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.theme.textTheme.titleLarge,
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else if (dataGridCell.columnName == 'Progress') {
            int process = dataGridCell.value ?? 0;
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: LinearPercentIndicator(
                animation: true,
                lineHeight: 18.0,
                animationDuration: 1000,
                percent: process.toDouble() / 100,
                center: Text(
                  "$process%",
                  style: TextStyle(
                      fontSize: 12.0,
                      color: Get.isDarkMode
                          ? Colors.black
                          : Get.theme.primaryColorLight),
                ),
                progressColor: Get.isDarkMode
                    ? AppTheme.colors.darkTheme4
                    : Get.theme.primaryColor,
                barRadius: Radius.circular(16),
                backgroundColor: AppTheme.colors.disableBtnLight,
              ),
            );
          } else if (dataGridCell.columnName == 'LastReadAt') {
            if (dataGridCell.value > 0) {
              return Container(
                  //padding: EdgeInsets.symmetric(horizontal: 16.0),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.blueGrey),
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  //padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.blueGrey),
                  ));
            }
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall?.copyWith(
                      color: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Colors.blueGrey),
                ));
          }
        }).toList());
  }
}
